package com.shiyun.marker.generator.file;

import cn.hutool.core.io.FileUtil;
import com.shiyun.marker.model.DataModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class DynamicFileGenerator {

    public static void doGenerator(String inputPath,String outputPath,Object dataModel) throws IOException, TemplateException {
        //判断输出路径文件是否存在
        if(!FileUtil.exist(outputPath)) {
            FileUtil.touch(outputPath);
        }
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_32);
        File inputFile = new File(inputPath);
        File templateDir = inputFile.getParentFile();
        configuration.setDirectoryForTemplateLoading(templateDir);
        configuration.setDefaultEncoding("utf-8");
        String templateName = inputFile.getName();
        Template template = configuration.getTemplate(templateName);
        Writer out = new FileWriter(outputPath);
        template.process(dataModel,out);
        out.close();
    }
}
